package org.example.com.Excutor;

import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DailyScheduler {

    public static void scheduleDailyTask(Runnable task, int hour, int minute, int second) {
        // 获取当前时间
        LocalTime now = LocalTime.now();
        long initialDelay = calculateInitialDelay(now, hour, minute, second);

        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 初始延迟后执行一次，之后每天执行一次
        scheduler.scheduleAtFixedRate(task, initialDelay, TimeUnit.DAYS.toSeconds(1), TimeUnit.SECONDS);
    }

    private static long calculateInitialDelay(LocalTime now, int targetHour, int targetMinute, int targetSecond) {
        long nowSeconds = now.toSecondOfDay();
        long targetSeconds = LocalTime.of(targetHour, targetMinute, targetSecond).toSecondOfDay();

        long delay = targetSeconds - nowSeconds;
        if (delay <= 0) {
            delay += TimeUnit.DAYS.toSeconds(1); // 如果今天已过目标时间，则推迟到明天
        }
        return delay;
    }
}